import 'package:customer/extension/extension_widget.dart';
import 'package:customer/utils/snackbar.dart';
import 'package:fluent_ui/fluent_ui.dart';
import '../../db/entity/ProductBean.dart';
import '../../main.dart';
import '../../widgets/gyy_dialog.dart';
import '../../widgets/gyy_theme.dart';

///新增 修改 （产品）

class AddProductPage extends StatefulWidget {
  final String title;
  final int? id;
  const AddProductPage({Key? key, required this.title, this.id}) : super(key: key);
  @override
  State<AddProductPage> createState() => _AddProductState();
}


class _AddProductState extends State<AddProductPage> {

  var productDao = database.productDao;
  ProductBean? productBean;

  TextEditingController productNameCon = TextEditingController();
  TextEditingController productCodeCon = TextEditingController();
  TextEditingController unitPriceCon = TextEditingController();
  TextEditingController allergenCon = TextEditingController();

  TextEditingController typesettingFeeCon = TextEditingController();
  TextEditingController printingFeeCon = TextEditingController();
  TextEditingController discountCon = TextEditingController();
  TextEditingController remarksCon = TextEditingController();

  loadProduct() async{
    productBean = await productDao.findById(widget.id!);
    debugPrint(productBean?.productCode);
    setState(() {

    });
    if(productBean != null) {
      productNameCon.text = productBean!.productName;
      productCodeCon.text = productBean!.productCode;
      unitPriceCon.text = productBean!.unitPrice.toString();
      typesettingFeeCon.text = productBean!.typesettingFee.toString();
      printingFeeCon.text = productBean!.printingFee.toString();
      allergenCon.text = productBean!.allergen;
      discountCon.text = productBean!.discount.toString();
      remarksCon.text = productBean!.remarks;
    }
  }

  @override
  void initState() {
    super.initState();
    if(widget.id != null) {
      loadProduct();
    }
  }

  @override
  Widget build(BuildContext context) {
    final theme = FluentTheme.of(context);


    bool checkInput() {
      if(productNameCon.text.isEmpty) {
        showMessage(context, '请输入产品名称');
        return false;
      }
      if(productCodeCon.text.isEmpty) {
        showMessage(context, '请输入产品编号');
        return false;
      }
      if(unitPriceCon.text.isEmpty) {
        showMessage(context, '请输入产品单价');
        return false;
      }
      if(typesettingFeeCon.text.isEmpty) {
        showMessage(context, '请输入产品排版费');
        return false;
      }
      if(printingFeeCon.text.isEmpty) {
        showMessage(context, '请输入产品打印费');
        return false;
      }
      return true;
    }

    //保存
    saveProduct(String name, String code, {int? id}) {
      var bean = ProductBean(
          id: id,
          productName:name,
          productCode:code,
          unitPrice: int.parse(unitPriceCon.text),
          allergen: allergenCon.text,
          typesettingFee: int.parse(typesettingFeeCon.text),
          printingFee: int.parse(printingFeeCon.text),
          discount: int.parse(discountCon.text.isEmpty ? '0' : discountCon.text),
          remarks: remarksCon.text,
          createTime:  DateTime.now(),
          updateTime: DateTime.now());
      if(id == null) {
        productDao.insertOne(bean);
      } else {
        productDao.updateOne(bean);
      }
      Navigator.pop(context, DialogConstant.ok);
    }

    return SingleChildScrollView(
      padding: EdgeInsets.all(20),
      child: Column(
        children: [
          sizeBoxV10,
          Row(
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
              spacer,
              Text(widget.title, style: theme.typography.title, ),
              spacer,
              IconButton(icon: const Icon(FluentIcons.chrome_close), onPressed: (){
                Navigator.pop(context, DialogConstant.cancel);
              })
            ],
          ),
          sizeBoxV10,
          Row(children:  [
            Expanded(child: GyyTextBox(
                header: '产品名称', controller: productNameCon
            )),
            Expanded(child: GyyTextBox(
                header: '产品编号', readOnly: widget.id != null, controller: productCodeCon
            )),
            Expanded(child: GyyTextBox(
              header: '产品单价', controller: unitPriceCon,
            )),

            Expanded(child: GyyTextBox(
              header: '印刷费', controller: printingFeeCon,
            )),
          ]),
          sizeBoxV5,
          Row(children:  [
            Expanded(child: GyyTextBox(
              header: '过敏原', controller: allergenCon,
            )),
            Expanded(child: GyyTextBox(
              header: '排版费', controller: typesettingFeeCon,
            )),
            Expanded(child: GyyTextBox(
              header: '折扣', controller: discountCon,
            )),

            Expanded(child: GyyTextBox(
              header: '备注', controller: remarksCon,
            )),
          ]),
          Container(
            constraints: BoxConstraints.tight(Size(10, 200)),
          ),

          Flex(
            direction: Axis.horizontal,
            children: [
              Expanded(
                  flex: 1,
                  child: FilledButton(
                      child: Text(widget.title), onPressed: () async{
                    var name = productNameCon.text;
                    var code = productCodeCon.text;
                    debugPrint('产品：' + name  + '  ' + code);

                    if(!checkInput()) {
                      return;
                    }
                    if(widget.id == null) {
                      saveProduct(name, code);
                    } else {
                      saveProduct(name, code, id: widget.id);
                    }
                  }).padding(const EdgeInsets.symmetric(horizontal: 50),))

              // sizeBoxH5,
              // FilledButton(child: Text('查询产品'), onPressed: () async{
              //   List<ProductBean> list  = await database.productDao.findAll();
              //   for (var element in list) {debugPrint(element.toJson().toString());}
              // }),
              // sizeBoxH5,
              // FilledButton(child: Text('删除所有产品'), onPressed: () async{
              //   database.productDao.deleteAll();
              // })

            ],
          ),

        ],
      ),
    );
  }

}




